<template>
  <div >
    <van-nav-bar
  title="购物车"
  left-text="返回"
  right-text="编辑"
  left-arrow
  @click-left="$router.go(-1)"
  @click-right="onClickRight"
/>
    <van-notice-bar
        left-icon="volume-o"
        text="优惠券：满39减2元，满59减5元，满79减8元,满99元减15元"
    />

    <van-cell is-link @click="showPopup">距离{{this.couponPrice}}元满减，还差{{ this.numPrice }}元 ，去凑单</van-cell>
    <van-action-sheet v-model="show" title="商品详情" @close="shuaxin">
      <div class="content">
        <van-card
            :price="goods.price"
            tag="低价"
            :desc="goods.description"
            :title="goods.name"
            :thumb="goods.imgUrl"
            v-for="goods in goodsList" :key="goods.id+''"
        >
          <template #footer>
            <van-icon name="shopping-cart" size="30" @click="addCarts(goods)"/>
          </template>
        </van-card>

      </div>
    </van-action-sheet>

<van-divider
  :style="{ color: '#1989fa', borderColor: '#1989fa', padding: '0 16px' }"
>
  购物车商品信息
</van-divider>

    <van-checkbox-group v-model="result" :disabled="isEditing">
      <van-checkbox :name="item.id" v-for="item in cartsList" :key="item.id" @click="changeChecked(item.id)" >
        <van-swipe-cell>
        <van-card
            :num="item.cartsNum"
            :price="item.price"
            :title="item.goodsName"
            :thumb="item.imgUrl"
        />
        <van-stepper v-model="item.cartsNum" v-show="isEditing" @change="stepperChange(item)"/>
          <template #right>
            <van-button square text="删除" type="danger" class="delete-button" @click="deleteCartsGoods(item.id)" />
          </template>
        </van-swipe-cell>
      </van-checkbox>
    </van-checkbox-group>

    <van-divider /><van-divider /><van-divider /><van-divider /><van-divider /><van-divider /><van-divider /><van-divider />

<van-submit-bar :price="this.cartsTotal * 100" button-text="提交订单" :fixed="false" @submit="addOrders">
  <!-- <van-checkbox v-model="checkedAll" :disabled="isEditing">全选</van-checkbox> -->
</van-submit-bar>


  </div>
  
</template>

<script>
import { Toast } from 'vant';
import { Button } from 'vant';
import { Card } from 'vant';
import { SubmitBar } from 'vant';
import { SwipeCell } from 'vant';
import { NavBar } from 'vant';
import { Icon } from 'vant';
import { Sticky } from 'vant';
import { Checkbox } from 'vant';
import { CheckboxGroup } from 'vant';
import { Divider } from 'vant';
import { NoticeBar } from 'vant';
import { Stepper } from 'vant';
import { Popup } from 'vant';
import { Cell } from 'vant';
import { ActionSheet } from 'vant';
import { Form } from 'vant';
import { Field } from 'vant';

import 'vant/lib/index.css';
export default {
  components: {
    [Card.name]: Card,
    [Button.name]: Button,
    [SubmitBar.name]: SubmitBar,
    [SwipeCell.name]: SwipeCell,
    [NavBar.name]: NavBar,
    [Icon.name]: Icon,
    [Sticky.name]: Sticky,
    [Checkbox.name]: Checkbox,
    [CheckboxGroup.name]: CheckboxGroup,
    [Divider.name]: Divider,
    [NoticeBar.name]: NoticeBar,
    [Stepper.name]: Stepper,
    [Popup.name]: Popup,
    [Cell.name]: Cell,
    [ActionSheet.name]: ActionSheet,
    [Form.name]: Form,
    [Field.name]: Field,
  },

  data() {
    return {
      username: '',
      password: '',
      active: 'carts',
      cartsList: [],
      cartsTotal:0,
      goodsList:[],
      //是一个展示选中的元素的数组
      result: [],
      show: false,
      //编辑状态的设置
      isEditing:false,
      //相减金额
      numPrice:0 ,
      //优惠券金额
      couponPriceArray:[39,59,79,99],
      couponPrice:0
    }
  },
  computed: {
    checkedAll() {
      return this.result.length == this.cartsList.length
    }
  },
  methods: {
    shuaxin(){
      this.queryCarts();
      this.queryCount();
    },
    onSubmit(values) {
      console.log('submit', values);
    },
    showPopup(){
      this.show = true;
      this.queryGoodsByPrice()
    },
    onClickRight() {
      this.isEditing = !this.isEditing;
      this.queryCarts();
      this.queryCount();
    },
    //添加订单
    addOrders(){
        let cartsIds=[];
        cartsIds=this.result;
        this.$axios.post('api/app/addOrders',cartsIds)
      .then(res=>{
          console.log(res.data);
        if(res.data.code == 200){
          Toast.success('下单成功');
          this.$router.push({name:'orders',
            params:{"oderId":res.data.data,
                    "cartsTotal":this.cartsTotal}})
        }else if (res.data.code==2007){
          Toast({
            message: res.data.msg,
            icon: 'https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fc-ssl.duitang.com%2Fuploads%2Fblog%2F202105%2F08%2F20210508130624_69eb3.thumb.1000_0.jpeg&refer=http%3A%2F%2Fc-ssl.duitang.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1681361606&t=aba4c7190cf84ce52c440ae41cd669fd',
          });

        }else if (res.data.code==2008){
          Toast.fail(res.data.msg);
        }
      })

    },
    addCarts(goods){
      let phone = sessionStorage.getItem("phone");
      let carts ={};
      // 获取数量
      carts.cartsNum =1;
      // 商品id
      carts.goodsId=goods.id;
      carts.price=goods.price;
      carts.phone=phone;
      this.$axios.post('api/app/addUserCarts',carts)
          .then(res=>{

                if(res.data.code == 200){
                  Toast.success('添加成功');
                }
         })
    },
    queryGoodsByPrice(){
      this.$axios.get('api/app/queryGoodsByPrice')
      .then(res=> {
        console.log(res.data)
            if (res.data.code == 200) {
              this.goodsList = res.data.data;
              console.log(this.goodsList);
            }
            })
    },

    queryCarts() {
      let phone = sessionStorage.getItem("phone");
      this.$axios.get('api/app/queryCarts?phone=' + phone)
          .then(res => {
            console.log(res.data)
            if (res.data.code == 200) {
              // console.log(ref.data)
              this.cartsList = res.data.data;
         

              //进购物车默认全选
              this.cartsList.map(item => {
                item.checked == 1 ? this.result.push(item.id) : "";
              })
            }
          })
    },
    queryCount() {
      let phone = sessionStorage.getItem("phone");
      this.$axios.get('api/app/queryCount?phone=' + phone)
          .then(res => {
            console.log(res.data)
              this.cartsTotal = res.data.data.cartsAmount;
            this.computePrice();
          })
    },

    changeChecked(id){
      if(this.isEditing)return;
      this.$axios.get('api/app/updateChecked?id=' + id)
          .then(res => {
             this.queryCount();
            this.computePrice();
            })
      },
        stepperChange(item){
          let phone = sessionStorage.getItem("phone");
          let carts ={};
          // 获取数量
          carts.id= item.id;
          carts.cartsNum =item.cartsNum;
          carts.goodsId=item.goodsId;
          carts.phone=phone;
          this.$axios.post('api/app/updateCartNum',carts)
              .then(res=>{
                console.log(res.data)
                if(res.data.code==200){
                  this.cartsList = res.data.data;
                }
              })
          this.computePrice();
         },
        computePrice(){
          //  this.cartsTotal//总数
          // couponPriceArray//数组
          // couponPrice//距离多少
          // numPrice//还差多少
          let arr = this.couponPriceArray;
          for (let i = 0; i < arr.length;  i++) {

            if(arr[i]>this.cartsTotal)
            {
              this.couponPrice = arr[i];
              this.numPrice = (arr[i]-this.cartsTotal).toFixed(2);
              break;
            }

            if(this.cartsTotal>this.couponPriceArray[3])
            {
              this.couponPrice = arr[3];
              this.numPrice = 0;
              break;

            }
          }

        },
    //删除购物车商品
    deleteCartsGoods(id){
      this.$axios.get('api/app/deleteCartsGoods?id='+id)
          .then(res=> {
            if(res.data.code==200){
              Toast.success('删除成功');
              this.result=[],
              this.queryCarts();
              this.queryCount();
            }
          })
    }
    },
    created() {
      this.queryCarts();
      this.queryCount();
    }

}
</script>

<style lang="less" scoped>

  .van-submit-bar{
   bottom: 50px
  }

  .content {
    padding: 16px 16px 160px;
  }
  /deep/.van-popup--center{
    flex:1;
  }

  /deep/.van-checkbox__label{
  flex:1;
  }
  .van-checkbox-group{
    background-color: ghostwhite;
    padding: .1rem .15rem;

  }
  .van-checkbox{
    border-bottom: 1px solid #475669;
  }
  .van-notice-bar{
    border-top: 1px solid #475669;

  }
  .van-stepper{
    text-align: right;
  }
  .van-button--square{
    height: 100%;
  }
</style> 